﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.IO;
using System.Windows.Controls;
using Caliburn.Micro;

namespace OI.ViewModels
{
    public class DownloadReadyViewModel : Screen
    {
        public Stream Data { get; private set; }
        public DatasetDetailsOptionsPanelViewModel.Modes Mode { get; private set; }

        public DownloadReadyViewModel(Stream data, DatasetDetailsOptionsPanelViewModel.Modes mode)
        {
            Data = data;
            Mode = mode;
            DisplayName = "Download is ready";
        }


        public void Cancel()
        {
            TryClose();
        }


        public void Save()
        {
            if (Data != null)
            {
                var sfd = new SaveFileDialog();

                if (Mode == DatasetDetailsOptionsPanelViewModel.Modes.Data)
                {
                    sfd.Filter = "CSV Files|*.csv";
                }
                else if (Mode == DatasetDetailsOptionsPanelViewModel.Modes.Map)
                {
                    sfd.Filter = "Shapefiles(Zip)|*.zip";
                }

                bool? dialogResult = sfd.ShowDialog();
                if (dialogResult.Value)
                {
                    using (Stream fs = sfd.OpenFile())
                    {
                        int length = Convert.ToInt32(Data.Length);
                        var byteResult = new byte[length];

                        Data.Read(byteResult, 0, length);
                        fs.Write(byteResult, 0, byteResult.Length);
                        fs.Close();
                    }
                }
            }
            TryClose();
        }
    }
}
